package com.toutou.base.bindhelper

import android.annotation.SuppressLint
import android.content.res.Resources
import android.graphics.Color
import android.graphics.Outline
import android.view.Gravity
import android.view.View
import android.view.ViewOutlineProvider
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import androidx.core.widget.PopupWindowCompat
import androidx.databinding.BindingAdapter
import com.toutou.base.R
import com.toutou.base.util.DensityUtil


class PopBDAdapter {
    companion object {
        data class PopItem(
            var leftIconTxt: String = "",
            var leftIconBackgroundColor: Int = Color.BLUE,
            var leftIconSize: Float = 12f,
            var leftIconRadius: Float = 2f,
            var text: String = "",
        )

        @SuppressLint("ResourceType")
        @JvmStatic
        @BindingAdapter(
            value = ["popItemSelectDelegate", "popItemTextSize", "popArray", "defaultSelectItem"],
            requireAll = true
        )
        fun initTextSelectPopWindow(
            view: View,
            popItemSelectDelegate: PopItemSelectDelegate?,
            popItemTextSize: Float,
            popArray: Array<PopItem>?,
            defaultSelectItem: Int
        ) {
            if (view.tag is PopupWindow || popItemSelectDelegate == null || popArray == null) {
                return
            }

//            view绘制完成之后
            view.post {
                val popupView = LinearLayout(view.context)
                popupView.orientation = LinearLayout.VERTICAL
                popupView.layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
                popupView.setBackgroundColor(Color.argb(128, 0, 0, 0))
                popupView.setOnClickListener { (view.tag as PopupWindow).dismiss() }
                for (i in popArray.indices) {
                    val itemPopLayout = LinearLayout(view.context)
                    itemPopLayout.layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    itemPopLayout.orientation = LinearLayout.HORIZONTAL
                    itemPopLayout.gravity = Gravity.CENTER
                    itemPopLayout.setBackgroundResource(if (i == popArray.size - 1) R.drawable.filter_bg_select_last else R.drawable.filter_bg_select)
                    itemPopLayout.isSelected = i == defaultSelectItem
                    itemPopLayout.setOnClickListener {
                        val parent = it.parent as LinearLayout
                        for (pItem in parent.children) {
                            pItem.isSelected = false
                        }
                        it.isSelected = true
                        (view.tag as PopupWindow).dismiss()
                        popItemSelectDelegate.selectItem(i)
                    }

                    val padding = (Resources.getSystem().displayMetrics.density * 15).toInt()
                    itemPopLayout.setPadding(padding, padding, padding, padding)

//region 左侧图标
                    if (popArray[i].leftIconTxt.isNotEmpty()) {
                        val leftIcon = TextView(view.context)
                        leftIcon.layoutParams = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT
                        ).apply {
                            marginEnd = (Resources.getSystem().displayMetrics.density * 4).toInt()
                        }
                        leftIcon.gravity = Gravity.CENTER
                        leftIcon.text = popArray[i].leftIconTxt
                        leftIcon.setTextColor(Color.WHITE)
                        leftIcon.setBackgroundColor(popArray[i].leftIconBackgroundColor)
                        val iconPadding = (Resources.getSystem().displayMetrics.density * 3).toInt()
                        leftIcon.setPadding(iconPadding, 0, iconPadding, 0)
                        leftIcon.textSize = popArray[i].leftIconSize
//                       设置圆角
                        leftIcon.outlineProvider = object : ViewOutlineProvider() {
                            override fun getOutline(view: View?, outline: Outline?) {
                                outline?.setRoundRect(
                                    0,
                                    0,
                                    view!!.width,
                                    view.height,
                                    Resources.getSystem().displayMetrics.density * popArray[i].leftIconRadius
                                )
                            }
                        }
                        leftIcon.clipToOutline = true
                        itemPopLayout.addView(leftIcon)
                    }
//                    endregion

//                    region 文字
                    val popItem = TextView(view.context)
                    popItem.layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    popItem.text = popArray[i].text
                    popItem.textSize = popItemTextSize
                    popItem.setTextColor(
                        ContextCompat.getColorStateList(
                            view.context,
                            R.drawable.filter_text_select
                        )
                    )
                    popItem.isSelected = i == defaultSelectItem
                    itemPopLayout.addView(popItem)
                    //endregion

                    popupView.addView(itemPopLayout)

                }

//                获取view在屏幕中的位置
                val locationArray = IntArray(2)
//            获取底部导航栏的高度·适配非全面屏
                val navigationBarHeight: Int = ViewCompat.getRootWindowInsets(view.rootView)
                    ?.getInsets(WindowInsetsCompat.Type.navigationBars())?.bottom ?: 0
                view.getLocationOnScreen(locationArray)
                val popupWindow = object : PopupWindow(
                    popupView,
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    view.rootView.height - locationArray[1] - view.height - navigationBarHeight - view.paddingTop - view.paddingBottom,
                    true
                ) {
                    override fun dismiss() {
                        super.dismiss()
                        view.isActivated = false
                    }
                }
                view.tag = popupWindow
            }
        }

        /**
         * @param popShow 是否显示popWindow
         * @param yoff y轴偏移量
         * @param curSelectItem 当前选中的item
         */
        @JvmStatic
        @BindingAdapter(value = ["popShow", "yoff"], requireAll = false)
        fun popShow(view: View, popShow: Boolean, yoff: Int?) {
            if (view.tag !is PopupWindow) {
                return
            }

//            刷新popwindow的高度·防止在第一次测绘的时候，view因父布局被隐藏，导致父布局高度为0，从而计算错误----示例在库存列表（可嵌套搜索）
            val locationArray = IntArray(2)
            view.getLocationOnScreen(locationArray)

//            获取底部导航栏的高度·适配非全面屏
            val navigationBarHeight: Int = ViewCompat.getRootWindowInsets(view.rootView)
                ?.getInsets(WindowInsetsCompat.Type.navigationBars())?.bottom ?: 0

//            设置y轴偏移量
            val disYOff = DensityUtil.dip2px(view.context, yoff?.toFloat() ?: 0f)

            (view.tag as PopupWindow).height =
                view.rootView.height - locationArray[1] - view.height - navigationBarHeight - disYOff

            if (popShow) {
                PopupWindowCompat.showAsDropDown(
                    view.tag as PopupWindow,
                    view,
                    0,
                    disYOff,
                    Gravity.BOTTOM
                )
                view.isActivated = true
            } else {
                (view.tag as PopupWindow).dismiss()
            }
        }
    }

    fun interface PopItemSelectDelegate {
        fun selectItem(position: Int)
    }
}